package com.tiger.log.core.aop.business;

import com.tiger.log.common.entity.SysRecordLog;
import com.tiger.log.core.processing.business.JsonProcessing;
import com.tiger.log.server.service.SysRecordLogService;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;

/**
 * @ClassName PostJsonAop
 * @Description TODO
 * @Author huxuehao
 **/
@Aspect
@Component
public class JsonAop {

    private final JsonProcessing jsonProcessing;
    private final SysRecordLogService sysRecordLogService;

    public JsonAop(JsonProcessing jsonProcessing, SysRecordLogService sysRecordLogService) {
        this.jsonProcessing = jsonProcessing;
        this.sysRecordLogService = sysRecordLogService;
    }

    @Pointcut("@annotation(com.tiger.log.common.annotation.business.json.JsonCollect)")
    public void postJsonPointCut(){

    }

    @Around("postJsonPointCut()")
    public Object around(ProceedingJoinPoint joinPoint) throws Throwable {
        if (jsonProcessing.isIllegal(joinPoint)) {
            return joinPoint.proceed();
        }
        SysRecordLog recordLog = new SysRecordLog();
        Object res;
        try {
            /* 执行前的处理 */
            jsonProcessing.proceedPreProcessing(recordLog, joinPoint);
            /* 执行 */
            res = joinPoint.proceed();
            /* 执行后的处理 */
            jsonProcessing.proceedPostProcessing(recordLog, res, false);
        } catch (Exception e) {
            /* 出现异常后的后置处理 */
            jsonProcessing.proceedPostProcessing(recordLog, null, true);
            throw e;
        } finally {
            /* 异步的日志生成*/
            sysRecordLogService.asyncGenLog(recordLog);
        }
        return res;
    }
}
